<?php
class TTT_Myfilter_Block_Adminhtml_Catalog_Product_Grid extends Mage_Adminhtml_Block_Catalog_Product_Grid
{
	protected $_entity = TTT_Myfilter_Model_Entity::PRODUCT;
	protected $_showAllRecords       = false;
	public function __construct()
    {
    	$this->_showAllRecords = true;
        parent::__construct();
    }
    
	protected function _prepareLayout()
	{
		// Set Additional Save Current Filter Button
		$this->setChild('myfilter_button',
		$this->getLayout()->createBlock('adminhtml/widget_button')
				->setData(array(
						'id'		=>	'myfilter_button',
                    	'label'     =>  Mage::helper('adminhtml')->__('Save Current Filter As'),
                    	'onclick'   => 'askForSave()',
                    	'class'   	=> 'add'
                    ))
                    );
         // Adding JS Phtml file
         $this->setChild('filterjs',
         $this->getLayout()->createBlock('core/template')
        	 ->setTemplate('myfilter/filterjs.phtml')
         	->setSaveUrl($this->_getSaveFilterUrl())
         	->setGridBlock($this)
         	);
         return parent::_prepareLayout();
	}

	protected function _prepareCollection()
    {        
       $store = $this->_getStore();
        $collection = Mage::getModel('catalog/product')->getCollection()
            ->addAttributeToSelect('sku')
            ->addAttributeToSelect('name')
            ->addAttributeToSelect('attribute_set_id')
            ->addAttributeToSelect('type_id')
            ->joinField('qty',
                'cataloginventory/stock_item',
                'qty',
                'product_id=entity_id',
                '{{table}}.stock_id=1',
                'left')
            ->joinField('is_in_stock',
                'cataloginventory/stock_item',
                'is_in_stock',
                'product_id=entity_id',
                '{{table}}.stock_id=1',
                'left');;

        if ($store->getId()) {
            //$collection->setStoreId($store->getId());
            $adminStore = Mage_Core_Model_App::ADMIN_STORE_ID;
            $collection->addStoreFilter($store);
            $collection->joinAttribute('name', 'catalog_product/name', 'entity_id', null, 'inner', $adminStore);
            $collection->joinAttribute('custom_name', 'catalog_product/name', 'entity_id', null, 'inner', $store->getId());
            $collection->joinAttribute('status', 'catalog_product/status', 'entity_id', null, 'inner', $store->getId());
            $collection->joinAttribute('visibility', 'catalog_product/visibility', 'entity_id', null, 'inner', $store->getId());
            $collection->joinAttribute('price', 'catalog_product/price', 'entity_id', null, 'left', $store->getId());
        }
        else {
            $collection->addAttributeToSelect('price');
            $collection->joinAttribute('status', 'catalog_product/status', 'entity_id', null, 'inner');
            $collection->joinAttribute('visibility', 'catalog_product/visibility', 'entity_id', null, 'inner');
        }

        $this->setCollection($collection);
    	if ($this->getCollection()) {

            $this->_preparePage();

            $columnId = $this->getParam($this->getVarNameSort(), $this->_defaultSort);
            $dir      = $this->getParam($this->getVarNameDir(), $this->_defaultDir);
            $filter   = $this->getParam($this->getVarNameFilter(), null);

            if (is_null($filter)) {
                $filter = $this->_defaultFilter;
            }

            if (is_string($filter)) {
                $data = $this->helper('adminhtml')->prepareFilterString($filter);
                $this->_setFilterValues($data);
            }
            else if ($filter && is_array($filter)) {
                $this->_setFilterValues($filter);
            }
            else if(0 !== sizeof($this->_defaultFilter)) {
                $this->_setFilterValues($this->_defaultFilter);
            }

            if (isset($this->_columns[$columnId]) && $this->_columns[$columnId]->getIndex()) {
                $dir = (strtolower($dir)=='desc') ? 'desc' : 'asc';
                $this->_columns[$columnId]->setDir($dir);
                $this->_setCollectionOrder($this->_columns[$columnId]);
            }

            if (!$this->_isExport) {
                $this->getCollection()->load();
                $this->_afterLoadCollection();
            }
        } 
        $this->getCollection()->addWebsiteNamesToResult();
        return $this;
    }
    
	public function getSaveFilterButtonHtml()
	{
		return $this->getChildHtml('myfilter_button');
	}

	public function getFilterJsHtml()
	{
		return $this->getChildHtml('filterjs');
	}

	/**
	 * Adding the custom Button to the main buttons html
	 * Adding custom JS Also
	 * (non-PHPdoc)
	 * @see Mage_Adminhtml_Block_Widget_Grid::getMainButtonsHtml()
	 */
	public function getMainButtonsHtml()
	{
		$html = '';
		if($this->getFilterVisibility()){
			$html.= $this->getSaveFilterButtonHtml();
			$html.= $this->getFilterJsHtml();
			$html.= $this->getResetFilterButtonHtml();
			$html.= $this->getSearchButtonHtml();
		}
		return $html;
	}


	/**
	 * Creating a URL when the button is clicked
	 * @return URL to prepare save the current filter
	 */
	protected function _getSaveFilterUrl()
	{
		$filterVarName = $this->getVarNameFilter();
		$filterValue = $this->getRequest()->getParam($filterVarName, '');
		return Mage::helper("adminhtml")
			->getUrl("myfilter/adminhtml_index/saveajax/",
					array("entity" => $this->_entity)
			);
	}
	
	protected function _prepareColumns()
    {        
        $this->addColumnAfter('image', array(
            'header'    => Mage::helper('catalog')->__('Image'),
            'index'     => 'image',
        	'filter'	=> false,
            'sortable'	=> false,
        	'align'		=> 'center',
            'renderer'	=> 'Gold_Cmage_Block_Adminhtml_Widget_Grid_Column_Renderer_Image'
        ), 'entity_id');
        
        $this->addColumnAfter('is_in_stock',
            array(
                'header'=> Mage::helper('catalog')->__('Stock Status'),
                'width' => '50px',
                'type'  => 'options',
                'index' => 'is_in_stock',
            	'align'		=> 'center',
            	'options'=> array(
            	  '0'=> Mage::helper('catalog')->__('Out of Stock'),
            	  '1'=> Mage::helper('catalog')->__('In Stock'),
                ),
        ), 'qty');
        parent::_prepareColumns();
    	if (!Mage::getSingleton('admin/session')->isAllowed('catalog/products/edit_product'))
    	{
    		$this->removeColumn('action');
    	}
        return $this;
    }

    public function getRecordCount()
    {
    	if ($this->_showAllRecords)
    	{
    		return $this->getCollection()->getSize();
    	}
    	
    	return false;
    }
    
	protected function _prepareMassaction()
    {        
        $this->getMassactionBlock()->addItem('product_print', array(
             'label'=> Mage::helper('catalog')->__('Product Print'),
             'url'  => $this->getUrl('*/*/productPrint'),
        ));

		parent::_prepareMassaction();
		
		if (!Mage::getSingleton('admin/session')->isAllowed('catalog/products/delete_product'))
    	{
    		$this->getMassactionBlock()->removeItem('delete');
    	}
		
		
		if (!Mage::getSingleton('admin/session')->isAllowed('catalog/products/change_status'))
    	{
    		$this->getMassactionBlock()->removeItem('status');
    	}
		
        return $this;
    }
    
	public function getRowUrl($row)
    {    	
    	if (!Mage::getSingleton('admin/session')->isAllowed('catalog/products/edit_product'))
    	{
    		return '';
    	}
        return $this->getUrl('*/*/edit', array(
            'store'=>$this->getRequest()->getParam('store'),
            'id'=>$row->getId())
        );
    }
    
	private function removeColumn($columnId)
    {
    	if ($this->getColumn($columnId))
    	{
    		unset($this->_columns[$columnId]);
    	}
    }

}